<?php

namespace Data;

class Article extends Base {

	const ARTICLE_TMP_VIEW_NUM = 'article_tmp_view_num';

	const SIMPLE_FIELDS = 'ArticleId,UserId,CategoryId,Title,Cover,ImgList,CreateTime,UpdateTime,ViewNumber,Status';

	public function saveArticle($articleId, $userId, $categoryId, $title, $content, $cover, $imgList) {
		$data = array(
			'UserId' => $userId,
			'CategoryId' => $categoryId,
			'Title' => $title,
			'Content' => $content,
			'Cover' => $cover,
			'ImgList' => $imgList,
			'CreateTime' => time(),
			'UpdateTime' => time(),
			'Status' => self::IS_YES,
			'IsDel' => self::IS_NO,
		);
		if (!$articleId) {
			return $this->insert($data);
		} else {
			unset($data['CreateTime']);
			unset($data['UserId']);
			$condition = array(
				'ArticleId' => $articleId,
				'UserId' => $userId,
			);
			$this->where($condition)->update($data);
			return $articleId;
		}
	}

	public function findArticle($pager, $getContent = false, $categoryId) {
		$condition = array();
		if ($categoryId) {
			$condition['CategoryId'] = $categoryId;
		}
		$condition['Status'] = self::IS_YES;
        $condition['IsDel'] = self::IS_NO;
		$select = self::SIMPLE_FIELDS;
		if ($getContent) {
			$select .= ',Content';
		}
		$this->select($select);
		$this->where($condition)->pager($pager);
		$this->order('ArticleId desc');
		$result = $this->findAll();
		$articleIds = array();
		foreach ($result as & $val) {
			$val['ViewNumber'] = $this->getCacheArticleView($val['ArticleId'], $val['ViewNumber']);
			$articleIds[] = $val['ArticleId'];
		}
		if ($articleIds) {
			$idToCount = \Data\Comments::instance()->getCountByIds($articleIds);
		}
		foreach ($result as & $val) {
			$val['CommentNumber'] = !empty($idToCount[$val['ArticleId']]) ? (int) $idToCount[$val['ArticleId']] : 0;
		}
		return $result;
	}

	public function increaseView($articleId) {
		$redis = $this->getRedis();
		$key = self::ARTICLE_TMP_VIEW_NUM;
		$redis->hincrby($key, $articleId, 1);
	}

	private function getCacheArticleView($articleId, $now = 0) {
		$redis = $this->getRedis();
		$key = self::ARTICLE_TMP_VIEW_NUM;
		$num = $redis->hGet($key, $articleId);
		$num = (int) $num;
		if ($num > 20) {
			$sql = 'update Article set ViewNumber = ViewNumber + ' . ($num + 1) . ' where ArticleId = ' . $articleId;
			$this->exec($sql);
			$redis->hSet($key, $articleId, 0);
		}
		return $num + $now;
	}

	public function getDetailById($articleId) {
		$condition = array(
			'ArticleId' => $articleId,
			'Status' => self::IS_YES,
            'IsDel' => self::IS_NO,
		);
		$detail = $this->where($condition)->findOne();
		$detail['ViewNumber'] = $this->getCacheArticleView($detail['ArticleId'], $detail['ViewNumber']);
		return $detail;
	}

	public function findArticleByUserId($pager, $userId, $categoryId = 0) {
		$condition = array();
		$condition['UserId'] = $userId;
		if ($categoryId) {
			$condition['CategoryId'] = $categoryId;
		}
        $condition['Status'] = self::IS_YES;
        $condition['IsDel'] = self::IS_NO;
		$this->where($condition);
		$this->select(self::SIMPLE_FIELDS);
		$this->order('ArticleId desc');
		$this->pager($pager);
		$result = $this->findAll();
		return $result;
	}

    public function getUserArticleCountByUserId($userId, $categoryId = 0) {
        $condition = array();
        $condition['UserId'] = $userId;
        if ($categoryId) {
            $condition['CategoryId'] = $categoryId;
        }
        $condition['Status'] = self::IS_YES;
        $condition['IsDel'] = self::IS_NO;
        $this->where($condition);
        $count = $this->count();
        return $count;
    }

	public function categoryArticleNumberByUserId($userId) {
		$condition = array(
			'UserId' => $userId,
			'Status' => self::IS_YES,
            'IsDel' => self::IS_NO,
		);
		$result = $this->select('count(1) as Number, CategoryId')->where($condition)->group('CategoryId')->findAll();
		$categoryIdToNumber = array();
		foreach ($result as $val) {
			$categoryIdToNumber[$val['CategoryId']] = $val['Number'];
		}
		return $categoryIdToNumber;
	}

	public function getRightArticles($limit = 5) {
		$condition = array(
			'Status' => self::IS_YES,
            'IsDel' => self::IS_NO,
			'Cover !=' => '',
		);
		$this->where($condition);
		$this->select(self::SIMPLE_FIELDS);
		$this->order('ArticleId desc');
		$this->limit($limit);
		$result = $this->findAll();
		return $result;
	}

	public function getUserOtherArticles($userId, $articleId, $limit = 5) {
		$condition = array(
			'UserId' => $userId,
			'Status' => self::IS_YES,
			'IsDel' => self::IS_NO,
			'ArticleId !=' => $articleId,
		);
		$result = $this->select(self::SIMPLE_FIELDS)->where($condition)->order('ArticleId desc')->limit($limit)->findAll();
		return $result;
	}

    public function delByIdAndUserId($articleId, $userId) {
        $condition = array(
            'ArticleId' => (int) $articleId,
            'UserId' => (int) $userId,
        );
        $this->where($condition)->update(array('IsDel' => self::IS_YES));
    }
}